package com.sky.service.impl;

import com.sky.context.ThreadLocalUtil;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {


    @Autowired
    private AddressBookMapper addressBookMapper;

    // 条件查询
    @Override
    public List<AddressBook> getList(AddressBook addressBookParam) {
        return addressBookMapper.getList(addressBookParam);
    }

    // 新增地址
    @Override
    public void save(AddressBook addressBook) {
        // 1.参数校验
        // 2.补全信息
        addressBook.setUserId(ThreadLocalUtil.getCurrentId());
        addressBook.setIsDefault(0); // 非默认
        // 3.调用mapper新增
        addressBookMapper.insert(addressBook);
    }
    // 根据id查询
    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    // 修改地址
    @Override
    public void updateById(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
    }

    // 根据id查询
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    // 设置默认地址
    @Transactional
    @Override
    public void setDefault(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(ThreadLocalUtil.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);
    }
}
